package org.skydiveapphd;

import org.skydiveapphd.ui.FragmentHelper;
import org.skydiveapphd.interfaces.SkydiveTypeNotifier;
import org.skydiveapplibrary.R;
import org.skydiveapplibrary.repository.SkydiveTypeRepository;
import org.skydiveapplibrary.ui.SkydiveTypeSelectListAdapter;

import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

public class SkydiveTypeSelectListActivity extends BaseListFragment
{	
	public static SkydiveTypeSelectListActivity newInstance(Bundle args) 
	{
		SkydiveTypeSelectListActivity f = new SkydiveTypeSelectListActivity();
		f.setArguments(args);
		return f;
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState)
    { 
    	super.onCreate(savedInstanceState);
    }
        
    @Override
    public void onResume()
    {
    	super.onResume();

    	// init view
    	getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    	setHeaderText(R.string.select_skydive_type_label);
    	setBottomButtonVisibility(View.GONE);
    	
    	loadData();
    }
    
    @Override
    protected void onTopButtonClick()
    {
    	FragmentHelper.getInstance().openFragment(SkydiveTypeEditActivity.newInstance(new Bundle()), android.R.id.tabhost, 
				Constants.TAG_SKYDIVE_TYPE_EDIT, getFragmentManager());
    }
    
    @Override
	public void onListItemClick(ListView listView, View view, int indx, long id)
    {
    	// get current selection
    	int previousSelectedId = getArguments().getInt(Constants.EXTRA_SKYDIVE_TYPE_ID, -1);
    	int newSelectedId = (int)id;
    	
    	SkydiveTypeNotifier f = (SkydiveTypeNotifier) getFragmentManager().findFragmentByTag(getArguments().getString(Constants.EXTRA_FRAG_TAG));
    	
    	// if different than previous
    	if (previousSelectedId != newSelectedId)
    		f.updateSkydiveType(newSelectedId);
    	
		getFragmentManager().popBackStack();
    }

    private void loadData()
    {
    	// populate skydive types
    	SkydiveTypeRepository repository = new SkydiveTypeRepository(getActivity());
    	SkydiveTypeSelectListAdapter adapter = new SkydiveTypeSelectListAdapter(
				getActivity(),
				repository.getSkydiveTypes());
		setListAdapter(adapter);
		
		// set initial selection
		int selectedId = this.getArguments().getInt(Constants.EXTRA_SKYDIVE_TYPE_ID, -1);
		for (int index = 0; index < adapter.getCount(); index++)
		{
			getListView().setItemChecked(index,
					adapter.getItems().get(index).getId() == selectedId); 
		}
    }
} 